//
//  DMNativeStrategyParser.m
//  DualMediationSDK
//
//  Created by YeJary on 2025/1/15.
//  Copyright © 2025 DualMediation. All rights reserved.
//

#import "DMNativeStrategyParser.h"
#import "../../Utils/Logger/IMLogUtils.h"
#import "../../API/AdStrategy/IMAdStrategyManager.h"
#import "DMNativeTypes.h"

@interface DMNativeStrategyParser ()

/**
 * 原生广告策略数据缓存
 * 格式：{
 *   "SCENE_NATIVE_SETTLEMENT": {
 *     "enabled": true,
 *     "position": "bottom",
 *     "wait_time": 5,
 *     "max_show_count": 3,
 *     "cooldown_time": 30,
 *     "priority": 1
 *   },
 *   "SCENE_NATIVE_SETTLEMENT2": {
 *     "enabled": true,
 *     "position": "top",
 *     "wait_time": 3,
 *     "max_show_count": 5,
 *     "cooldown_time": 60,
 *     "priority": 2
 *   }
 * }
 */
@property (nonatomic, strong) NSMutableDictionary<NSString *, NSDictionary *> *nativeStrategies;

@end

@implementation DMNativeStrategyParser

#pragma mark - 单例

+ (instancetype)sharedParser {
    static DMNativeStrategyParser *instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[DMNativeStrategyParser alloc] init];
    });
    return instance;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        _nativeStrategies = [NSMutableDictionary dictionary];
        [IMLogUtils info:IMLogTagAd format:@"📋 DMNativeStrategyParser 初始化完成"];
    }
    return self;
}

#pragma mark - 公共接口

- (BOOL)parseNativeStrategy:(NSDictionary *)strategyData {
    [IMLogUtils info:IMLogTagAd format:@"📋 开始解析原生广告策略数据"];
    
    if (!strategyData || ![strategyData isKindOfClass:[NSDictionary class]]) {
        [IMLogUtils error:IMLogTagAd format:@"❌ 原生广告策略数据无效"];
        return NO;
    }
    
    @try {
        // 清除旧策略
        [self.nativeStrategies removeAllObjects];
        
        // 解析每个场景的策略
        for (NSString *sceneName in strategyData.allKeys) {
            NSDictionary *sceneStrategy = strategyData[sceneName];
            
            if ([sceneStrategy isKindOfClass:[NSDictionary class]]) {
                // 验证策略数据完整性
                if ([self validateNativeSceneStrategy:sceneStrategy forScene:sceneName]) {
                    self.nativeStrategies[sceneName] = sceneStrategy;
                    [IMLogUtils debug:IMLogTagAd format:@"✅ 解析原生广告场景策略成功: %@", sceneName];
                } else {
                    [IMLogUtils warning:IMLogTagAd format:@"⚠️ 原生广告场景策略数据不完整，跳过: %@", sceneName];
                }
            } else {
                [IMLogUtils warning:IMLogTagAd format:@"⚠️ 原生广告场景策略格式错误，跳过: %@", sceneName];
            }
        }
        
        [IMLogUtils info:IMLogTagAd format:@"✅ 原生广告策略解析完成，共解析 %lu 个场景", (unsigned long)self.nativeStrategies.count];
        return YES;
        
    } @catch (NSException *exception) {
        [IMLogUtils error:IMLogTagAd format:@"❌ 解析原生广告策略时发生异常: %@", exception.reason];
        return NO;
    }
}

- (BOOL)isNativeEnabledForScene:(NSString *)sceneName {
    if (!sceneName || sceneName.length == 0) {
        [IMLogUtils warning:IMLogTagAd format:@"⚠️ 场景名称为空，返回默认值 NO"];
        return NO;
    }
    
    NSDictionary *strategy = self.nativeStrategies[sceneName];
    if (!strategy) {
        [IMLogUtils debug:IMLogTagAd format:@"🔍 未找到场景 %@ 的原生广告策略，返回默认值 NO", sceneName];
        return NO;
    }
    
    NSNumber *enabled = strategy[@"enabled"];
    BOOL result = enabled ? [enabled boolValue] : NO;
    [IMLogUtils debug:IMLogTagAd format:@"📋 场景 %@ 原生广告启用状态: %@", sceneName, result ? @"启用" : @"禁用"];
    return result;
}

- (nullable NSString *)getNativePositionForScene:(NSString *)sceneName {
    if (!sceneName || sceneName.length == 0) {
        [IMLogUtils warning:IMLogTagAd format:@"⚠️ 场景名称为空，返回默认位置 bottom"];
        return @"bottom";
    }
    
    NSDictionary *strategy = self.nativeStrategies[sceneName];
    if (!strategy) {
        [IMLogUtils debug:IMLogTagAd format:@"🔍 未找到场景 %@ 的原生广告策略，返回默认位置 bottom", sceneName];
        return @"bottom";
    }
    
    NSString *position = strategy[@"position"];
    NSString *result = (position && position.length > 0) ? position : @"bottom";
    [IMLogUtils debug:IMLogTagAd format:@"📋 场景 %@ 原生广告位置: %@", sceneName, result];
    return result;
}

- (NSInteger)getNativeWaitTimeForScene:(NSString *)sceneName {
    if (!sceneName || sceneName.length == 0) {
        [IMLogUtils warning:IMLogTagAd format:@"⚠️ 场景名称为空，返回默认等待时间 0"];
        return 0;
    }
    
    NSDictionary *strategy = self.nativeStrategies[sceneName];
    if (!strategy) {
        [IMLogUtils debug:IMLogTagAd format:@"🔍 未找到场景 %@ 的原生广告策略，返回默认等待时间 0", sceneName];
        return 0;
    }
    
    NSNumber *waitTime = strategy[@"wait_time"];
    NSInteger result = waitTime ? [waitTime integerValue] : 0;
    [IMLogUtils debug:IMLogTagAd format:@"📋 场景 %@ 原生广告等待时间: %ld 秒", sceneName, (long)result];
    return result;
}

- (NSInteger)getNativeMaxShowCountForScene:(NSString *)sceneName {
    if (!sceneName || sceneName.length == 0) {
        [IMLogUtils warning:IMLogTagAd format:@"⚠️ 场景名称为空，返回默认最大展示次数 1"];
        return 1;
    }
    
    NSDictionary *strategy = self.nativeStrategies[sceneName];
    if (!strategy) {
        [IMLogUtils debug:IMLogTagAd format:@"🔍 未找到场景 %@ 的原生广告策略，返回默认最大展示次数 1", sceneName];
        return 1;
    }
    
    NSNumber *maxShowCount = strategy[@"max_show_count"];
    NSInteger result = maxShowCount ? [maxShowCount integerValue] : 1;
    [IMLogUtils debug:IMLogTagAd format:@"📋 场景 %@ 原生广告最大展示次数: %ld", sceneName, (long)result];
    return result;
}

- (NSInteger)getNativeCooldownTimeForScene:(NSString *)sceneName {
    if (!sceneName || sceneName.length == 0) {
        [IMLogUtils warning:IMLogTagAd format:@"⚠️ 场景名称为空，返回默认冷却时间 0"];
        return 0;
    }
    
    NSDictionary *strategy = self.nativeStrategies[sceneName];
    if (!strategy) {
        [IMLogUtils debug:IMLogTagAd format:@"🔍 未找到场景 %@ 的原生广告策略，返回默认冷却时间 0", sceneName];
        return 0;
    }
    
    NSNumber *cooldownTime = strategy[@"cooldown_time"];
    NSInteger result = cooldownTime ? [cooldownTime integerValue] : 0;
    [IMLogUtils debug:IMLogTagAd format:@"📋 场景 %@ 原生广告冷却时间: %ld 秒", sceneName, (long)result];
    return result;
}

- (NSInteger)getNativePriorityForScene:(NSString *)sceneName {
    if (!sceneName || sceneName.length == 0) {
        [IMLogUtils warning:IMLogTagAd format:@"⚠️ 场景名称为空，返回默认优先级 1"];
        return 1;
    }
    
    NSDictionary *strategy = self.nativeStrategies[sceneName];
    if (!strategy) {
        [IMLogUtils debug:IMLogTagAd format:@"🔍 未找到场景 %@ 的原生广告策略，返回默认优先级 1", sceneName];
        return 1;
    }
    
    NSNumber *priority = strategy[@"priority"];
    NSInteger result = priority ? [priority integerValue] : 1;
    [IMLogUtils debug:IMLogTagAd format:@"📋 场景 %@ 原生广告优先级: %ld", sceneName, (long)result];
    return result;
}

- (void)clearAllStrategies {
    [IMLogUtils info:IMLogTagAd format:@"🗑️ 清除所有原生广告策略缓存"];
    [self.nativeStrategies removeAllObjects];
}

- (NSDictionary *)getAllNativeStrategies {
    return [self.nativeStrategies copy];
}

#pragma mark - 策略获取接口

- (void)fetchAndParseNativeStrategyWithCompletion:(void(^)(BOOL success, NSError * _Nullable error))completion {
    [IMLogUtils info:IMLogTagAd format:@"🔄 开始从广告策略接口获取原生广告策略数据"];
    
    if (!completion) {
        [IMLogUtils warning:IMLogTagAd format:@"⚠️ 完成回调为空，无法返回结果"];
        return;
    }
    
    // 获取广告策略管理器
    IMAdStrategyManager *strategyManager = [IMAdStrategyManager sharedManager];
    if (!strategyManager) {
        NSError *error = [NSError errorWithDomain:@"DMNativeStrategyParser" 
                                             code:-1001 
                                         userInfo:@{NSLocalizedDescriptionKey: @"广告策略管理器不可用"}];
        [IMLogUtils error:IMLogTagAd format:@"❌ 广告策略管理器不可用"];
        completion(NO, error);
        return;
    }
    
    // 从策略管理器获取原生广告相关场景的策略
    NSMutableDictionary *nativeStrategies = [NSMutableDictionary dictionary];
    
    // 获取原生结算界面策略
    id nativeSettlementStrategy = [strategyManager getConditionForScene:IMAdSceneNativeSettlement];
    if (nativeSettlementStrategy && [nativeSettlementStrategy isKindOfClass:[NSDictionary class]]) {
        nativeStrategies[@"SCENE_NATIVE_SETTLEMENT"] = nativeSettlementStrategy;
        [IMLogUtils info:IMLogTagAd format:@"✅ 获取SCENE_NATIVE_SETTLEMENT策略成功"];
    }
    
    // 获取原生结算界面2策略
    id nativeSettlement2Strategy = [strategyManager getConditionForScene:IMAdSceneNativeSettlement2];
    if (nativeSettlement2Strategy && [nativeSettlement2Strategy isKindOfClass:[NSDictionary class]]) {
        nativeStrategies[@"SCENE_NATIVE_SETTLEMENT2"] = nativeSettlement2Strategy;
        [IMLogUtils info:IMLogTagAd format:@"✅ 获取SCENE_NATIVE_SETTLEMENT2策略成功"];
    }
    
    // 解析获取到的策略数据
    BOOL parseSuccess = [self parseNativeStrategy:nativeStrategies];
    
    if (parseSuccess) {
        [IMLogUtils info:IMLogTagAd format:@"✅ 原生广告策略获取和解析成功"];
        completion(YES, nil);
    } else {
        NSError *error = [NSError errorWithDomain:@"DMNativeStrategyParser" 
                                             code:-1002 
                                         userInfo:@{NSLocalizedDescriptionKey: @"原生广告策略解析失败"}];
        [IMLogUtils error:IMLogTagAd format:@"❌ 原生广告策略解析失败"];
        completion(NO, error);
    }
}

#pragma mark - 私有方法

/**
 * 验证原生广告场景策略数据的完整性
 * @param strategy 策略数据
 * @param sceneName 场景名称
 * @return 是否有效
 */
- (BOOL)validateNativeSceneStrategy:(NSDictionary *)strategy forScene:(NSString *)sceneName {
    if (!strategy || ![strategy isKindOfClass:[NSDictionary class]]) {
        [IMLogUtils warning:IMLogTagAd format:@"⚠️ 场景 %@ 策略数据格式无效", sceneName];
        return NO;
    }
    
    // 检查必需字段
    NSArray *requiredFields = @[@"enabled"];
    for (NSString *field in requiredFields) {
        if (!strategy[field]) {
            [IMLogUtils warning:IMLogTagAd format:@"⚠️ 场景 %@ 缺少必需字段: %@", sceneName, field];
            return NO;
        }
    }
    
    // 检查可选字段的类型
    if (strategy[@"position"] && ![strategy[@"position"] isKindOfClass:[NSString class]]) {
        [IMLogUtils warning:IMLogTagAd format:@"⚠️ 场景 %@ position字段类型错误", sceneName];
        return NO;
    }
    
    if (strategy[@"wait_time"] && ![strategy[@"wait_time"] isKindOfClass:[NSNumber class]]) {
        [IMLogUtils warning:IMLogTagAd format:@"⚠️ 场景 %@ wait_time字段类型错误", sceneName];
        return NO;
    }
    
    if (strategy[@"max_show_count"] && ![strategy[@"max_show_count"] isKindOfClass:[NSNumber class]]) {
        [IMLogUtils warning:IMLogTagAd format:@"⚠️ 场景 %@ max_show_count字段类型错误", sceneName];
        return NO;
    }
    
    if (strategy[@"cooldown_time"] && ![strategy[@"cooldown_time"] isKindOfClass:[NSNumber class]]) {
        [IMLogUtils warning:IMLogTagAd format:@"⚠️ 场景 %@ cooldown_time字段类型错误", sceneName];
        return NO;
    }
    
    if (strategy[@"priority"] && ![strategy[@"priority"] isKindOfClass:[NSNumber class]]) {
        [IMLogUtils warning:IMLogTagAd format:@"⚠️ 场景 %@ priority字段类型错误", sceneName];
        return NO;
    }
    
    return YES;
}

@end
